<template>
  <div class="case-list" v-if="new Date().getTime()">
    <div class="list-serach">
      <div class="admin-search">
        <a-select
          :default-value="options[0]"
          style="width: 150px"
          :options="options"
          @change="handleSelectChange"
          v-model="adminSearchId"
          showSearch
        >
        </a-select>

        <a-select
          v-if="optionsClassify.length > 1"
          default-value="全部分类"
          style="width: 150px"
          :options="optionsClassify"
          @change="handleClassifyChange"
          showSearch
          notFoundContent="请选择分类"
        >
        </a-select>
        <a-input-search
          size="default"
          v-model="searchCaseId"
          enter-button
          @search="getCaseByIdAdmin"
          placeholder="请输入案例id"
        />
      </div>
      <a-button type="primary" @click="resetSearch">重置搜索条件</a-button>
    </div>
    <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :data-source="caseList"
      :pagination="false"
      :rowKey="(record) => record.id"
    >
      <span slot="customTitle">案例id</span>
      <span slot="pic" slot-scope="text, record">
        <img
          style="
            width: 100px;
            height: 100px;
            border-radius: 5%;
            box-shadow: 2px 2px 5px #333333;
          "
          :src="record.cover"
        />
      </span>
      <span slot="action" slot-scope="text, record">
        <a-button
          type="primary"
          style="margin-right: 8px"
          icon="eye"
          @click="showDetail(record.id)"
          >查看</a-button
        >
        <a-button
          type="danger"
          style="margin-right: 8px"
          icon="delete"
          @click="delSingle(record.id)"
          >删除</a-button
        >
      </span>
    </a-table>
    <div class="bottom">
      <div class="button-group">
        <a-button type="danger" class="del-list-btn" @click="delAll"
          >删除选中</a-button
        >
      </div>
      <a-pagination
        class="pageTab"
        :current="current"
        :page-size-options="pageSizeOptions"
        :total="caseNum"
        :show-total="(total) => `共 ${caseNum} 条`"
        :page-size="limit"
        :default-current="1"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        @change="pageChange"
      />
      <a-modal
        centered
        title="删除案例"
        v-model="delModalVisible"
        @ok="delOk"
        @cancel="delNo"
      >
        <p>此操作不可逆！确认删除？</p>
      </a-modal>
    </div>
  </div>
</template>

<script>
import {
  getAllAdminProjectApi,
  getAllCaseByProjectIdApi,
  deleteCaseApi,
  getCaseByIdAdminApi,
  getAllCaseAdminApi,
  getAllClassifyByProjectIdApi,
  getAllCaseByClassifyApi,
} from '@/services/superAdmin';
import moment from 'moment';
export default {
  data() {
    return {
      columns: [
        {
          title: '案例id',
          dataIndex: 'id',
          key: 'caseId',
          align: 'center',
        },
        {
          title: '案例标题',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '封面图片',
          dataIndex: 'cover',
          key: 'cover',
          scopedSlots: { customRender: 'pic' },
          align: 'center',
        },
        {
          title: '项目名',
          dataIndex: 'projectName',
          key: 'projectName',
          align: 'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
          align: 'center',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      adminSearchId: 0,
      caseNum: 0, //案例数量
      pageSizeOptions: ['5', '10', '15', '20', '25'], //每页案例数选择
      current: 1, //当前页面
      limit: 5, //每页多少条
      caseList: [],
      selectedRowKeys: [], //选择的列数
      delModalVisible: false,
      currentCaseId: 0,
      action: '', // 删除单条还是多条
      options: [{ label: '全部项目', value: 0 }], // 项目id下拉框选项
      optionsClassify: [{ label: '全部分类', value: 0 }],
      searchCaseId: '',
    };
  },
  async created() {
    if (this.$route.query.id) {
      this.adminSearchId = this.$route.query.id;
      this.searchByProId(this.limit, 0);
    } else {
      this.getAllCaseAdmin(this.limit, 0);
    }
    this.getAllAdminProject();
  },
  methods: {
    handleClassifyChange(value) {
      getAllCaseByClassifyApi({ id: value }).then((res) => {
        this.caseList = res.data.Cases;
      });
    },
    getAllClassifyByProjectId(proID) {
      getAllClassifyByProjectIdApi({ id: proID }).then((res) => {
        res.data.rows.forEach((ele) => {
          this.optionsClassify.push({ label: ele.name, value: ele.id });
        });
      });
    },
    handleSelectChange(value) {
      this.adminSearchId = value;
      if (value == 0) {
        this.getAllCaseAdmin(this.limit, 0);
        this.optionsClassify = [{ label: '全部分类', value: 0 }];
        return;
      }
      this.searchByProId();
      this.getAllClassifyByProjectId(value);
    },
    // 获取全部项目
    getAllAdminProject() {
      getAllAdminProjectApi().then((res) => {
        res.data.rows.forEach((ele) => {
          this.options.push({
            label: `${ele.Projects[0].name} id:${ele.Projects[0].id}`,
            value: ele.Projects[0].id,
          });
        });
      });
    },
    // 重置搜索
    async resetSearch() {
      this.searchCaseId = '';
      this.adminSearchId = 0;
      this.$message.success(`重置搜索条件成功`, 1.5);
      this.getAllCaseAdmin(this.limit, 0);
      this.current = 1;
      this.caseList = [];
      this.optionsClassify = [{ label: '全部分类', value: 0 }];
    },
    // admin获取所有新闻列表
    async getAllCaseAdmin(limit, offset) {
      let res = await getAllCaseAdminApi({
        limit,
        offset,
      });
      this.caseList = res.data.rows;
      this.caseList.forEach((ele) => {
        ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
      });
      this.caseNum = res.data.count;
    },
    // 按项目id搜索，获取列表
    async searchByProId() {
      if (!this.adminSearchId) {
        return;
      }
      let offset = (this.current - 1) * this.limit;
      try {
        let res = await getAllCaseByProjectIdApi({
          id: this.adminSearchId - 0,
          limit: this.limit,
          offset,
        });
        this.caseList = [];
        this.caseList.push(...res.data.rows);
        if (res.data.count == 0) {
          this.$message.error('该项目下无案例,请重新选择', 1);
          setTimeout(() => {
            this.getAllCaseAdmin(this.limit, 0);
            this.current = 1;
          }, 1000);
          this.adminSearchId = 0;
          this.optionsClassify = [{ label: '全部分类', value: 0 }];
          return;
        }
        this.caseList.forEach((ele) => {
          ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
          ele.projectName = res.data.projectName;
        });
        this.caseNum = res.data.count;
      } catch (error) {
        this.$message.error(`请重新输入`, 1);
        this.optionsClassify = [{ label: '全部分类', value: 0 }];
        this.adminSearchId = 0;
      }
    },
    // 按id搜索
    async getCaseByIdAdmin() {
      if (!this.searchCaseId) {
        return;
      }
      this.adminSearchId = 0;
      this.optionsClassify = [{ label: '全部分类', value: 0 }];
      try {
        let res = await getCaseByIdAdminApi({
          id: this.searchCaseId - 0,
        });
        this.caseList = res.data ? [res.data] : [];
        if (this.caseList) {
          this.caseList[0].createdAt = moment(
            this.caseList[0].createdAt
          ).format('YYYY-MM-DD  HH:mm:ss');
        }
        this.caseNum = this.caseList.length;
      } catch (error) {
        this.searchCaseId = '';
        this.$message.error(`请重新输入`, 1);
        setTimeout(() => {
          this.getAllCaseAdmin(this.limit, 0);
          this.current = 1;
        }, 1000);
      }
    },
    // 跳转案例详情
    showDetail(id) {
      this.$router.push(`/case/caseDetail/${id}`);
    },
    // 删除单条modal框
    delSingle(id) {
      this.currentCaseId = id;
      this.delModalVisible = true;
      this.action = 'deleteSingle';
    },
    // 删除多条modal框
    delAll() {
      this.action = 'deleteAll';
      let flag = this.selectedRowKeys.length;
      if (flag == 0) {
        this.$message.error('未选中任何案例', 1);
      } else {
        this.delModalVisible = true;
      }
    },
    // 确认删除
    async delOk() {
      switch (this.action) {
        case 'deleteSingle': {
          let res = await this.delCase();
          res.code == 200 && this.$message.success(res.msg, 1);
          this.delModalVisible = false;
          break;
        }
        case 'deleteAll':
          this.delAllCase();
          break;
      }

      this.getAllCaseAdmin(this.limit, 0);
      this.current = 1;
    },
    //删除操作
    async delCase(id = this.currentCaseId) {
      this.currentCaseId = '';
      return await deleteCaseApi({ id });
    },
    // 删除多条的操作
    delAllCase() {
      let delArr = this.selectedRowKeys;
      try {
        delArr.map((ele) => {
          this.delCase(ele);
        });
      } catch (error) {
        this.$message.error('删除失败', 1);
      }
      this.$message.success(`成功删除${delArr.length}条案例`, 1);
      this.selectedRowKeys = [];
      this.delModalVisible = false;
    },
    // 取消删除
    delNo() {
      this.delModalVisible = false;
      this.$message.info('取消删除', 1);
    },
    // 多选
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.limit = pageSize;
      this.pageChange(current);
    },
    pageChange(current) {
      this.current = current;
      let offset = (this.current - 1) * this.limit;
      if (this.adminSearchId) {
        this.searchByProId();
        return;
      }
      this.getAllCaseAdmin(this.limit, offset);
    },
  },
};
</script>

<style lang="scss" scoped>
.add {
  margin-bottom: 10px;
}
.list-serach {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 1rem;
  .ant-input-search {
    width: 200px;
  }
  .admin-search {
    .ant-select {
      min-width: 80px;
      .ant-select-selection {
        display: flex;
        flex-direction: column;
      }
    }
  }
  .ant-input-group {
    display: flex;
  }
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
  .button-group {
    button {
      margin-right: 10px;
    }
  }
  .pageTab {
    text-align: right;
  }
  .del-list-btn {
    text-align: center;
  }
}
</style>
